// 消息内容参考：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/customer-message/receive.html
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const $c$ = cloud.database().command

// 云函数入口函数
exports.main = async (event, context) => {
  console.log("event", event)
  // 如果是接收到消息
  if (event.MsgType) {
    return saveMsgInput(event)
  }
  if (event.sendSubscribeMsg) {
    return sendSubscribeMsg(event)
  }
  if(event.sendUniformMessage){
    return sendUniformMessage()
  }
  return '参数错误'
}

// 保存消息
async function saveMsgInput(event) {
  let msgId = await getMsgId(event)
  let msgObj = getMsgObj(event)
  let saveResult = '保存结果'
  if (msgId) { // 如果已经存在数据则更新聊天列表
    saveResult = await db.collection('mynote').doc(msgId).update({
      data: {
        msgList: $c$.push(msgObj)
      }
    })
  } else { // 如果已经存在数据则更新聊天列表
    let chatObj = {
      msgList: [msgObj],
      userInfo: event.userInfo,
      CreateTime: event.CreateTime,
    }
    saveResult = db.collection('mynote').add({
      data: chatObj
    })
  }
  // let sendResult = await sendTemplateMsg(msgObj)
  // let sendResult = await sendCustomerMsg(msgObj)
  let sendResult = await sendUniformMessage(msgObj)
  saveResult.sendResult = sendResult
  return saveResult
}

// 获取已经保存的用户聊天
async function getMsgId(event) {
  let msgData = await db.collection('mynote').where({
    userInfo: {
      openId: event.userInfo.openId
    }
  }).get()
  console.log("getMsgId-msgData", msgData)
  let msgId = ''
  if (msgData.data && msgData.data.length > 0)
    msgId = msgData.data[0]._id
  console.log("getMsgId-msgId", msgId)
  return msgId
}

// 获取消息实体
function getMsgObj(event) {
  let msgObj = {
    CreateTime: '',
    FromUserName: '',
    ToUserName: '',
    MsgType: '',
    Content: '',
    PicUrl: '',
    MediaId: ''
  }
  for (let key in msgObj) {
    msgObj[key] = event[key] ? event[key] : '';
  }
  console.log("getMsgObj", msgObj)
  return msgObj
}

// 发送自定义消息
async function sendCustomerMsg(msgObj) {
  let msgData = {
    touser: cloud.getWXContext().OPENID,
    msgtype: msgObj.MsgType,
    text: {
      content: msgObj.Content
    }
  }
  const result = await cloud.openapi.customerServiceMessage.send(msgData)
  return result
}

// 发送统一的服务消息
async function sendUniformMessage() {
  let msgData = {
    thing1: {
      value: '个人超级工具箱'
    },
    thing8: {
      value: '测试订阅消息'
    },
    thing2: {
      value: '测试消息内容'
    },
    date3: {
      value: '2020-08-12 12:00'
    },
    thing7:{
      value: '点击本消息，查看详情'
    }
  }
  const result = await cloud.openapi.uniformMessage.send({
    touser: cloud.getWXContext().OPENID,
    weappTemplateMsg: {
      page: 'pages/index/index',
      data: msgData,
      formId: '2056',
      emphasisKeyword: "通知",
      templateId: 'X15zp3hfUUqyLMX2jj41BW7OwPi7h71_FNFhyY9GYC4',
    }
  })
  return result
}

// 发送模板消息
async function sendTemplateMsg(msgObj) {
  let msgData = {
    keyword1: {},
    keyword2: {},
    keyword3: {},
    keyword4: {},
    keyword5: {}
  }
  msgData.keyword1.value = msgObj.FromUserName
  msgData.keyword2.value = msgObj.MsgType + "消息"
  msgData.keyword3.value = msgObj.Content ? msgObj.Content : msgObj.PicUrl
  msgData.keyword4.value = timestampToTime(msgObj.CreateTime)
  msgData.keyword5.value = "点击本消息，查看详情"
  console.log("sendTemplateMsg", msgData)
  const sendResult = await cloud.openapi.templateMessage.send({
    touser: cloud.getWXContext().OPENID,
    weapp_template_msg: {
      page: 'pages/index/index',
      data: msgData,
      formId: '2056',
      emphasisKeyword: msgObj.FromUserName,
      templateId: 'X15zp3hfUUqyLMX2jj41BW7OwPi7h71_FNFhyY9GYC4',
    }
  })
  return sendResult
}

//将时间戳转换成正常时间格式
function timestampToTime(timestamp) {
  var date = new Date(Number(timestamp) * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
}


// 发送订阅消息
async function sendSubscribeMsg(event) {
  try {
    const wxContext = cloud.getWXContext()
    const result = await cloud.openapi.subscribeMessage.send({
      touser: wxContext.OPENID,
      page: 'pages/index/index',
      lang: 'zh_CN',
      data: {
        thing1: {
          value: '个人超级工具箱'
        },
        thing8: {
          value: '测试订阅消息'
        },
        thing2: {
          value: '测试消息内容'
        },
        date3: {
          value: '2020-08-12 12:00'
        },
        thing7:{
          value: '点击本消息，查看详情'
        }
      },
      templateId: 'X15zp3hfUUqyLMX2jj41BW7OwPi7h71_FNFhyY9GYC4',
      miniprogramState: 'developer'
    })
    return result
  } catch (err) {
    return err
  }
}